package com.mes.handler.collection;

import com.basis.utils.CodeGenerateRuleUtil;
import com.mes.data.EmesGroupStaff;
import com.mes.data.EmesProcess;
import com.mes.manufacture.data.*;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class EmesProcessDataInfoHandler extends BaseActionHandler {
	private static Logger logger = Logger.getLogger(EmesProcessDataInfoHandler.class);
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject result = new JSONObject();
		try {
			OBContext.setAdminMode();
			String userId = SessionInfo.getUserId();
			JSONObject request = new JSONObject(content);
			User user = OBDal.getInstance().get(User.class, userId);
			String method = request.getString("method");

			result.put("result", true);
			if ("getItemData".equals(method)) {
				String itemId = request.getString("itemId");
				this.setItemData(itemId, result);
			} else if ("getProcessInfo".equals(method)) {
				String processId = request.getString("processId");
				result.put("dcItem", getDcItem(processId));
				
				setManuOrderInfo(processId, result);
			} else if ("submit".equals(method)) {
				return this.submit(request, user);
			} else {
				if (user.getDefaultProcess() != null) {
					String defaultProcessId = user.getDefaultProcess().getId();
					result.put("processId", defaultProcessId);
				}
				
				result.put("allItem", this.getDCAllItem());
				result.put("userName", user.getName());
				
				String hql = "select new map(e.id as id, e.name as name, e.routeNo as routeNo) " +
						"from " + EmesProcess.ENTITY_NAME + " e where e.emesProcessRoute.organization.id = ?";
				Query query = OBDal.getInstance().getSession().createQuery(hql);
				
				query.setString(0,  user.getOrganization().getId());
				List<Map> list = query.list();
				if (list.isEmpty()) {
					result.put("result", false);
					result.put("text", "您所在的组织无工艺路线，请切换您所在组织结构!");
					return result;
				}
				JSONArray arr = new JSONArray();
				JSONObject obj = null;
				for (Map map : list) {
					obj = new JSONObject();
					obj.put("id", map.get("id"));
					obj.put("name", map.get("name"));
					obj.put("routeNo", map.get("routeNo"));
					arr.put(obj);
				}
				result.put("processList", arr);
			}
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("获取生产数据采集初始化信息异常：" + e.getMessage(), e);
			try {
				result.put("result", false);
				result.put("text", "获取生产数据采集初始化信息异常：" + e.getMessage());
			} catch (JSONException e1) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return result;
	}
	
	private void setManuOrderInfo(String processId, JSONObject result) throws Exception {
		String sql = "select p.name productName, p.value productCode, to_char(p.weight, '0.000') weight, o.code orderCode, o.qty, o.description, " +
				"	to_char(o.planed_date_from, 'YYYY-MM-DD') dateForm, to_char(o.planed_date_to, 'YYYY-MM-DD') dateTo " +
				"  from emeso_manuorder o, m_product p, emeso_manu_in_material im, emeso_manu_batch b" +
				" where p.m_product_id = im.m_product_id" +
				"   and im.emeso_manuorder_id = o.emeso_manuorder_id" +
				"   and im.emeso_manu_in_material_id = b.emeso_manu_in_material_id" +
				"   and b.emes_process_id = ?" +
				" order by start_time desc";
		
		Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		query.setString(0, processId);
		Map map = (Map)query.uniqueResult();
		
		if (map != null) {
			result.put("orderCode", map.get("ORDERCODE"));
			result.put("dateFrom", map.get("DATEFORM"));
			result.put("dateTo", map.get("DATETO"));
			result.put("qty", map.get("QTY"));
			result.put("orderDescription", map.get("DESCRIPTION"));

			result.put("weight", map.get("WEIGHT"));
			result.put("productCode", map.get("PRODUCTCODE"));
			result.put("productName", map.get("PRODUCTNAME"));
		}
	}
	/**
	 * 已有的采集项目
	 */
	private JSONArray getDcItem(String processId) throws Exception {
		JSONArray dcItems = new JSONArray();
		EmesProcess process = OBDal.getInstance().get(EmesProcess.class, processId);
		
		long seq = 0;
		List<EmesoDCProcessRelation> list = OBDal.getInstance().getSession().createQuery(
				"from " + EmesoDCProcessRelation.ENTITY_NAME + " r where r.emesProcess=?").setParameter(0, process).list();
		if (list == null || list.isEmpty()) {
			List<EmesoDCRouteOprRelation> oprList = OBDal.getInstance().getSession().createQuery(
					"from " + EmesoDCRouteOprRelation.ENTITY_NAME + " where emesProcessOpr=?").setParameter(0, process.getEmesProcessOpr()).list();
			
			for (EmesoDCRouteOprRelation rr : oprList) {
				if (rr.getEmesoDcGroup() != null) {
					List<EmesoDCGroupItem> dcList = rr.getEmesoDcGroup().getEmesoDCGroupItemList();// 模型组的采集项目列表
					for (EmesoDCGroupItem emesoDCGroupItem : dcList) {
						seq = emesoDCGroupItem.getSeqNo() + seq;
						dcItems.put(getDcItem(emesoDCGroupItem.getEmesoDcItem(), seq));
					}
				} else if (rr.getEmesoDcItem() != null) {
					seq ++;
					dcItems.put(getDcItem(rr.getEmesoDcItem(), seq));
				}
			}
		} else {
			for (EmesoDCProcessRelation pr : list) {
				if (pr.getEmesoDcGroup() != null) {
					List<EmesoDCGroupItem> dcList = pr.getEmesoDcGroup().getEmesoDCGroupItemList();// 模型组的采集项目列表
					for (EmesoDCGroupItem emesoDCGroupItem : dcList) {
						seq = emesoDCGroupItem.getSeqNo() + seq;
						dcItems.put(getDcItem(emesoDCGroupItem.getEmesoDcItem(), seq));
					}
				} else if (pr.getEmesoDcItem() != null) {
					seq ++;
					dcItems.put(getDcItem(pr.getEmesoDcItem(), seq));
				}
			}
		}
		return dcItems;
	}
	private JSONObject getDcItem(EmesoDCItem dcItem, long seq) throws Exception {
		JSONObject tmpJson = new JSONObject();
		tmpJson.put("name", dcItem.getName());
		tmpJson.put("type", dcItem.getDataType());
		tmpJson.put("id", dcItem.getId());
		tmpJson.put("seqNo", seq);
		tmpJson.put("value", "");
		if ("SELECTOR".equals(dcItem.getDataType())) {// 选项
			tmpJson.put("child", new JSONObject());// 选项列表
			for (EmesoDCEnumDataItem child : dcItem.getEmesoDcEnumData().getEmesoDCEnumDataItemList()) {
				tmpJson.getJSONObject("child").put(child.getId(), child.getResult());
			}
		}
		return tmpJson;
	}
	/**
	 * 所有的采集项目
	 */
	private JSONObject getDCAllItem() throws Exception {
		List<EmesoDCItem> list = OBDal.getInstance().createQuery(EmesoDCItem.class, "").list();
		JSONObject allItem = new JSONObject();
		for (EmesoDCItem item : list) {
			allItem.put(item.getId(), item.getName());
		}
		return allItem;
	}
	/**
	 * 获取 数据采集项目 中的选项
	 */
	private void setItemData(String itemId, JSONObject result) {
		try {
			EmesoDCItem emesoDCItem = OBDal.getInstance().get(EmesoDCItem.class, itemId);
			String type = emesoDCItem.getDataType();
			String id = emesoDCItem.getId();
			result.put("type", type);
			result.put("id", id);
			if ("SELECTOR".equals(type)) {// 选项
				String title = emesoDCItem.getEmesoDcEnumData().getName();
				result.put("title", title);
				result.put("child", new JSONObject());
				for (EmesoDCEnumDataItem item : emesoDCItem.getEmesoDcEnumData().getEmesoDCEnumDataItemList()) {
					result.getJSONObject("child").put(item.getId(), item.getResult());
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存数据采集项目
	 */
	private JSONObject submit(JSONObject request, User user) throws Exception {
		JSONObject responseResult = new JSONObject();

		String orderId = request.getString("orderId");//生产订单ID
		String processId = request.getString("processId");//工序ID
		double scrapWeight = request.getDouble("scrapWeight");//碎片重量
		long scrapQty = request.getLong("scrapQty");//碎片数量
		String description = request.getString("description");
		
		EmesoDataCollectionResult result = new EmesoDataCollectionResult();
		String code = CodeGenerateRuleUtil.getCode(EmesoDataCollectionResult.ENTITY_NAME, "code");
		result.setCode(code);
		result.setScrapQty(scrapQty);
		result.setScrapWeight(new BigDecimal(scrapWeight));
		result.setEmesProcess(OBDal.getInstance().get(EmesProcess.class, processId));
		result.setEmesoManuorder(OBDal.getInstance().get(EmesoManuOrder.class, orderId));
		result.setUser(user);
		
		//获取当前用户的班组
		List<EmesGroupStaff> staffList = OBDal.getInstance().createQuery(EmesGroupStaff.class, "where user.id = '" + user.getId() + "'").list();
		if (!staffList.isEmpty()) {
			result.setEmesGroup(staffList.get(0).getEmesGroup());
		}
		result.setDescription(description);
		
		OBDal.getInstance().save(result);
		
		//保存数据采集信息
		saveCollectionData(result, request.getJSONArray("arr"));

		OBDal.getInstance().flush();
		
		//记录碎片信息
		String sql = "{call Mes_DataCollection.scrap(?, ?, ?, ?, '')}";
		Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
		query.setParameter(0, processId);
		query.setParameter(1, scrapWeight);
		query.setParameter(2, scrapQty);
		query.setParameter(3, user.getId());
		query.executeUpdate();
		
		responseResult.put("result", true);
		responseResult.put("text", "提交成功！");
		return responseResult;
	}
	
	//保存生产采集数据
	private void saveCollectionData(EmesoDataCollectionResult result, JSONArray arr) throws Exception {
		long maxSeqNo = 10;
		for (int i = 0; i < arr.length(); i++) {
			JSONObject item = arr.getJSONObject(i);
			// 作业数据采集值
			EmesoDataCollectionResultValue resultValue = new EmesoDataCollectionResultValue();
			resultValue.setEmesoDcResult(result);
			resultValue.setDataType(item.getString("dataType"));
			if (item.has("seqNo")) {
				resultValue.setSeqNo(item.getLong("seqNo"));
				// 系统自带的先提交 追加的数据在后面
				maxSeqNo = resultValue.getSeqNo() > maxSeqNo ? resultValue.getSeqNo() : maxSeqNo;
			} else {
				maxSeqNo += 10;
				resultValue.setSeqNo(maxSeqNo);
			}
			
			// 数据采集项目
			EmesoDCItem emesoDCItem = OBDal.getInstance().get(EmesoDCItem.class, item.getString("id"));
			resultValue.setEmesoDcItem(emesoDCItem);
			resultValue.setValue(item.getString("value") == null ? "" : item.getString("value"));
			OBDal.getInstance().save(resultValue);
		}
	}
}
